from PyQt5.QtCore import QDate
from src.backend.beanfactory import BeanFactory
from docx import Document

from src.log import Logger


def contain(x,word):
    key_list=x.split(',')
    for k in key_list:
        for i,w in enumerate(word['three'].values.tolist()):
            if k in w:
                return word.iloc[i].at['two']

def count_correct(name,start_date:QDate,end_date:QDate,type:int,level):
    start_date=start_date.toString('yyyy-MM-dd')
    end_date=end_date.toString('yyyy-MM-dd')
    sql=f"select c.*,t.knowledge,t.level from " \
        f"(select * from correcting WHERE 1=1 and " \
        f"student='{name}' and date between '{start_date}' and '{end_date}' ) c \
LEFT JOIN (select * from topic where type={type} and level ={level}) t on c.topic_pos=t.id " \
        f"WHERE knowledge is not NULL and level is not null"
    Logger('app').get_logger().info(f'sql:{sql}')
    df=BeanFactory.getCursor().query(sql)
    word = BeanFactory.getKeyWord().word_df
    df['two']=df['knowledge'].apply(lambda x:contain(x,word))
    result=df[['two','right']].groupby(['two']).agg(count=('right', 'count'), sum=('right', 'sum'))
    # 重命名列
    result = result.rename(columns={'count': '总数', 'sum': '正确数'})
    return result

def generate_docx_data(student,start,end,type,level,count=5,correct_num=10):
    result=count_correct(student,start,end,type,level)
    # result['correct_rate'] = result['正确数'] / result['总数']
    result=result.loc[(result['正确数']<=correct_num)|(result['总数']<=count),:]
    points=result.index.values.tolist()
    ## 获取所有题目
    topics=BeanFactory.getCursor().query('select text,knowledge from topic')
    ## 获取所有关键词
    word = BeanFactory.getKeyWord().word_df
    ## 符合条件的关键词
    new_word=word.loc[word['two'].isin(points)]
    topics['two']=topics['knowledge'].apply(lambda x: contain(x, new_word))
    return topics.loc[topics['two'].notna()][['text']]